import os
from copy import deepcopy
import sys

def readFile(path):
    cArr = []
    with open(path, 'r', encoding="gb2312") as fp:
        for line in fp:
            if len(line.strip()) == 0 :
                continue
            lineArr = line.split('\\')
            cArr += lineArr
    resList = []
    templateMap = {
            "顾客名称" : '',
            "控制器型号": '',
            "遥控器型号": '',
            "控制器图号": '',
            "生产批号": '',
            "录入人员": '',
            "加工方式": '',
            "生产日期": '',
            "主码一": '',
            "副码一": '',
            "副码二": ''
        }
    for item in cArr:
        tem = item.split("=")
        k = tem[0].strip()
        if len(tem) < 2:
            continue            
        v = tem[1].strip()
        if k == '顾客名称':
            resList.append(deepcopy(templateMap))
        templateMap[k] = v
    resList = resList[1:]
    return resList

def writeFile(listCon, Root):
    for line in listCon:
        aDir = line['控制器型号']
        aFilename = line['生产批号']
        fileP = Root + aDir + '/' + aFilename + '.log'
        writeOne(fileP,line)

def writeOne(fileP,line):
    path = os.path.dirname(fileP)
    wStr = '' 
    for one in line:
        wStr += one + '=' + line[one] + '\\'
    wStr = wStr[:-1] + '\n'
    os.path.exists(path) or os.makedirs(path)
    with open(fileP,'a',encoding='gb2312') as fp:
        fp.write(wStr)
    pstr = fileP + " << " + wStr 
    print(pstr)

def getDirIndex(path):
    dirs = os.listdir(path)
    for one in dirs:
        dPath = path + one
        if not os.path.isdir(dPath) :
            continue
        with open(path + "dir.log", 'a',encoding="gb2312") as fp:
            fp.write(one+'\n')
        getFileIndex(dPath)

def getFileIndex(path):
    files = os.listdir(path)
    for one in files:
        (fileName, ext) = os.path.splitext(one)
        with open(path + "/index.txt", 'a',encoding="gb2312") as fp:
            fp.write(fileName +'\n')

if __name__ == "__main__":

    souceFile = './info_stor.log'
    if len(sys.argv[1:]) >= 1:
        souceFile = sys.argv[1]
    Root = os.path.dirname(souceFile) + '/Lib/'
    con = readFile(souceFile)
    writeFile(con, Root)
    getDirIndex(Root)
    msg = "is Ok!! you files in " + Root + "\nPress any key to exit"
    input(msg)